#include "mainpage.h"
#include "ui_mainpage.h"
#include "netmain.h"
#include <QTimer>
#include <QTime>
#include <QDebug>
#include <QPixmap>
#include <QImage>

MainPage::MainPage(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::MainPage),
    CarTimer(new QTimer)
{
    ui->setupUi(this);


    connect(CarTimer,&QTimer::timeout,
            this,&MainPage::getCarTimerTimeoutSlot);
    roundList.append(0);
    roundList.append(6);
    roundList.append(3);
    roundList.append(12);
    roundList.append(4);
    roundList.append(11);
    roundList.append(7);
    roundList.append(1);


    connect(NetMain::getObject(),&NetMain::LampControl,
            this,&MainPage::LampControlSlot);
    connect(NetMain::getObject(),&NetMain::setCarAlarmSig,
            this,&MainPage::setCarAlarmSlot);
    connect(NetMain::getObject(),&NetMain::setCarAlarmLightSig,
            this,&MainPage::setCarAlarmLightSlot);
    connect(NetMain::getObject(),&NetMain::setCarStatusSig,
            this,&MainPage::setCarStatusSlot);
    connect(NetMain::getObject(), &NetMain::newLamp,
            this, &MainPage::newLampSlot);
}

MainPage::~MainPage()
{
    delete ui;
}

void MainPage::getCarTimerTimeoutSlot()
{
    roundPos++;
    if(roundPos > 9)
    {
        roundIndex++;
        roundPos=0;
        if(roundIndex >= roundList.length())
        {
            roundIndex = 0;
        }
    }
    NetMain::getObject()->carPosChanged(roundList.at(roundIndex),roundPos);
}

void MainPage::on_btnSend_clicked()
{
    NetMain::getObject()->carPosChanged(ui->cbRoundId->currentIndex(), ui->cbRoundPos->currentIndex());
}


void MainPage::setCarAlarmSlot(bool sw)
{
    ui->cbAlarm->setChecked(sw);

}

void MainPage::setCarAlarmLightSlot(bool sw)
{
    ui->cbAlarmLigth->setChecked(sw);

}

void MainPage::setCarStatusSlot(bool sw)
{
    ui->cbStatus->setChecked(sw);
    if(sw)
    {
        CarTimer->start(500);

    }
    else {
        CarTimer->stop();

    }
}

void MainPage::newLampSlot(int roadId, int color)
{

    if(roundList.at(roundIndex) == roadId && color != 0)
      {
         if(roadId == 2 && roundPos == 9 )
         {
             CarTimer->stop();
         }
        else if(roadId == 3 && roundPos == 9)
         {
             CarTimer->stop();
         }
        else if(roadId == 6 && roundPos == 9)
          {
              CarTimer->stop();
          }
        else if(roadId == 8 && roundPos == 9)
          {
               CarTimer->stop();
          }
        else if(roadId == 11 && roundPos == 9)
          {
                CarTimer->stop();
          }
        else if(roadId == 13 && roundPos == 9)
          {
                CarTimer->stop();
          }

       }
    if(roundList.at(roundIndex) == roadId && color == 0 && roundPos == 9)
     {
        CarTimer->start(500);
     }
}

void MainPage::LampControlSlot(bool sw)
{
    ui->cbLight->setChecked(sw);


}
